<?php
namespace Core\Forms\Element;

use Phalcon\Di;

class Tags extends Text
{
    public function getValue()
    {
        $value = parent::getValue();
        if (is_string($value)) {
            $value = explode(',', $value);
        }
        $output = [];
        foreach ($value as $k => $v){
            if($v){
                $output[$k] = $v;
            }
        }

        return $output;
    }

    public function getDefault()
    {
        $default = parent::getDefault();
        if(is_array($default)){
            $default = implode(',',$default);
        }
        return $default;
    }

    public function render($attributes = null)
    {
        $di = Di::getDefault();
        if(!isset($this->_options['source'])){
            $this->_options['source'] = '';
        }

        $script =
<<<scription
$('#{$this->_name}').tagsInput({
    'width':'100%',
    'height':'44px',
    'defaultText':'添加新标签',
    autocomplete_url:'{$this->_options['source']}',
    autocomplete:{selectFirst:true,width:'100px',autoFill:true}
});
scription;

        $di->getShared('assets')
            ->addJs('jquery-tags', '//cdn.bootcss.com/jquery-tagsinput/1.3.6/jquery.tagsinput.min.js', 'footer')
            ->addCss('jquery-tags', '/library/jquery-tagsinput/jquery.tagsinput.min.css', 'footer')
            ->addInlineJs('bootstrap-datetimepicker-init-' . $this->_name, $script, 'footer');
        return parent::render($attributes);
    }
}
